package com.insigma.business.qrcode.soldier.util;

import com.google.common.collect.Maps;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;


public abstract class SecurityUtil {

    private SecurityUtil() {
    }

    
    public static String signRequest(Map<String, String> requestParamMap, String secret) {
        
        Map<String, String> sortedParams = new TreeMap<>(requestParamMap);
        Set<Entry<String, String>> paramSet = sortedParams.entrySet();

        
        final StringBuilder query = new StringBuilder(secret);
        for (Entry<String, String> param : paramSet) {
            if (StringUtils.isNotBlank(param.getKey()) && StringUtils
                    .isNotBlank(param.getValue())) {
                query.append("&").append(param.getKey()).append("=").append(param.getValue());
            }
        }

        return DigestUtils.sha256Hex(query.toString().getBytes(StandardCharsets.UTF_8));
    }

    public static void main(String[] args) {
        Map<String, String> map = Maps.newHashMap();
        map.put("userName", "name");
        map.put("userPhone", "phone");

        System.out.println(SecurityUtil.signRequest(map, "wmcstyjr2020@hz"));
    }

}
